//
//  AdvancedHapticManager.swift
//  ZD
//
//  Created by ZSC on 2025/5/18.
//

import SwiftUI
import CoreHaptics

// MARK: - 增强版触觉控制器
class AdvancedHapticManager: ObservableObject {
    private var engine: CHHapticEngine?
    private var supportsHaptics: Bool
    
    init() {
        // 检测设备支持情况
        supportsHaptics = CHHapticEngine.capabilitiesForHardware().supportsHaptics
        guard supportsHaptics else { return }
        
        do {
            engine = try CHHapticEngine()
            try engine?.start()
            configureEngineHandlers()
        } catch {
            print("Haptic引擎初始化失败: \(error)")
        }
    }
    
    private func configureEngineHandlers() {
        engine?.stoppedHandler = { reason in
            print("引擎停止原因: \(reason)")
            // 自动重启逻辑
            try? self.engine?.start()
        }
        
        engine?.resetHandler = {
            try? self.engine?.start()
        }
    }
    
    // 通用播放方法
    func playPattern(_ events: [CHHapticEvent]) {
        guard supportsHaptics, let engine = engine else { return }
        
        do {
            let pattern = try CHHapticPattern(events: events, parameters: [])
            let player = try engine.makePlayer(with: pattern)
            try player.start(atTime: 0)
        } catch {
            print("触觉播放错误: \(error)")
        }
    }
    
    // 预定义常用模式
    func playStandard(_ type: FeedbackType) {
        switch type {
        case .success:
            let event = CHHapticEvent(
                eventType: .hapticTransient,
                parameters: [
                    CHHapticEventParameter(parameterID: .hapticIntensity, value: 0.8),
                    CHHapticEventParameter(parameterID: .hapticSharpness, value: 0.7)
                ],
                relativeTime: 0
            )
            playPattern([event])
            
        case .warning:
            // 自定义警告模式
            let events = [
                CHHapticEvent(eventType: .hapticTransient, parameters: [], relativeTime: 0),
                CHHapticEvent(eventType: .hapticTransient, parameters: [], relativeTime: 0.2)
            ]
            playPattern(events)
            
        case .error:
            // 错误震动模式
            let events = [
                CHHapticEvent(eventType: .hapticContinuous, parameters: [], relativeTime: 0, duration: 0.5),
                CHHapticEvent(eventType: .hapticTransient, parameters: [], relativeTime: 0.5)
            ]
            playPattern(events)
        }
    }
    
    
    func playIntensityCurveEffect() {
        guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else {
            print("设备不支持高级触觉反馈")
            return
        }
        
        // 1. 创建参数曲线
        let intensityCurve = CHHapticParameterCurve(
            parameterID: .hapticIntensityControl,
            controlPoints: [
                CHHapticParameterCurve.ControlPoint(relativeTime: 0, value: 0.2),
                CHHapticParameterCurve.ControlPoint(relativeTime: 0.5, value: 1.0),
                CHHapticParameterCurve.ControlPoint(relativeTime: 1.0, value: 0.5)
            ],
            relativeTime: 0,    // 曲线起始时间
        )
        
        // 2. 创建连续震动事件
        let continuousEvent = CHHapticEvent(
            eventType: .hapticContinuous,
            parameters: [
                // 此处不需要设置intensity参数，由曲线控制
                CHHapticEventParameter(parameterID: .hapticSharpness, value: 0.7)
            ],
            relativeTime: 0,    // 与曲线同步开始
            duration: 2.0       // 必须与曲线时长一致
        )
        
        // 3. 创建触觉模式
        do {
            let pattern = try CHHapticPattern(
                events: [continuousEvent],
                parameterCurves: [intensityCurve] // 注入参数曲线
            )
            
            // 4. 创建并启动播放器
            let player = try engine?.makePlayer(with: pattern)
            try player?.start(atTime: 0)
            
        } catch {
            print("曲线震动播放失败: \(error.localizedDescription)")
        }
    }
}

enum FeedbackType {
    case success, warning, error
}

